<template>
  <div id="print-form-page" class="print-form">
    <el-button type="primary" size="small" class="print-btn no-print" @click="print">打 印</el-button>
    <div ref="printBox" class="print-box">
      <div class="print-box-title">{{ curStore.store_name }}</div>
      <div class="print-box-title">销售单</div>
      <div class="print-box-company">
        <label>购买单位: {{ orderData.company_name }}</label>
        <div class="print-box-date">
          <label class="order_no">{{ orderData.order_no }}</label>
          <label>购买日期: {{ handleDate(orderData.create_time) }}</label>
        </div>
      </div>
      <table>
        <tr>
          <td v-for="(column) in columns.filter(d => d.isPrint)" :key="column.key" class="print-label td-label-l">{{ column.title }}</td>
        </tr>
        <tr v-for="(item, index) in orderData.goods_list" :key="index">
          <template v-for="(column) in columns.filter(d => d.isPrint)">
            <td :key="column.key" class="print-label td-label-l">{{ handleRowResult(column.key, item) }}</td>
          </template>
          <!-- <td colspan="5" class="print-content">{{ bidder.name }}</td> -->
        </tr>
        <tr v-for="(item, index) in maxLength - orderData.goods_list.length" :key="'replenish'+index">
          <template v-for="(column) in columns.filter(d => d.isPrint)">
            <td :key="column.key" class="print-label td-label-l">{{ "" }}</td>
          </template>
        </tr>
        <tr>
          <template v-for="(column, index) in columns.filter(d => d.isPrint)">
            <td :key="column.key" class="print-label td-label-l">{{ getSummaries(index, column.key) }}</td>
          </template>
        </tr>
        <tr>
          <td class="print-label td-label-l">大写</td>
          <td :colspan="columns.filter(d => d.isPrint).length - 1" class="print-label td-label-l moneyStr">{{ moneyStr || '' }}</td>
        </tr>
      </table>
      <div class="print-box-foot">
        <div>单据说明:（白单：存根, 红单：客户, 黄单：财务）</div>
        <div>温馨提醒: 请在收到货物的2天内，及时确认当批货物的重量、数量、包装是否正确，如有任何差异，请在上述规定时间内与我司联系确认。以便我司能第一时间跟进解决，过期恕不受理。谢谢！{{ curStore.phone }}</div>
        <div>客户签收: </div>
      </div>
    </div>
  </div>
</template>
<script>
// import { bidder } from '@/api'
import curde from '@/mixins/curde';
export default {
  filters: {
    filterLowPrice(val) {
      if (!val) {
        return '0'
      }
      const strArr = (val + '').split('').reverse().join('').replace(/(\d{3})(?=\d)/g, '$1,').split('').reverse()
      return strArr.join('')
    }
  },
  mixins: [curde],
  props: {
    orderData: {
      type: Object,
      default: () => {
        return {
          customer_id: '',
          company_name: '',
          store_house_id: '',
          goods_list: [],
          total_num: 0,
          total_price: 0,
          discount: 1,
          remarks: '',
          order_type: '1'
        };
      }
    },
    columns: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      bidder: {
        bidSection: {
          bidSectionName: 'bidSectionName'
        },
        tenderProjectCode: 'tenderProjectCode',
        name: 'name',
        openingBank: 'openingBank',
        bankAccount: 'bankAccount',
        creatorName: 'creatorName',
        shouldReturnAmount: 'shouldReturnAmount',
        tenderAgencyName: 'tenderAgencyName',
        financeInputName: 'financeInputName',
        financeAuditName: 'financeAuditName',
        tenderProject: {}
      },
      upperShouldReturnAmount: '',
      maxLength: 10,
      moneyStr: ''
    }
  },
  mounted() {
    // this.detail()
  },
  methods: {
    // 金额数字转大写
    transform(money) {
      var cnMoney = '零元整';
      var strOutput = '';
      var strUnit = '仟佰拾亿仟佰拾万仟佰拾元角分';
      money += '00';
      var intPos = money.indexOf('.');
      if (intPos >= 0) {
        money = money.substring(0, intPos) + money.substr(intPos + 1, 2);
      }
      strUnit = strUnit.substr(strUnit.length - money.length);
      for (var i = 0; i < money.length; i++) {
        strOutput += '零壹贰叁肆伍陆柒捌玖'.substr(money.substr(i, 1), 1) + strUnit.substr(i, 1);
      }
      cnMoney = strOutput.replace(/零角零分$/, '整').replace(/零[仟佰拾]/g, '零').replace(/零{2,}/g, '零').replace(/零([亿|万])/g, '$1').replace(/零+元/, '元').replace(/亿零{0,3}万/, '亿').replace(/^元/, '零元');
      return cnMoney;
    },
    // 总计
    getSummaries(index, prop) {
      const columns = this.columns.filter(d => d.isPrint);
      console.log('getSummaries--columns==', columns);
      const data = this.orderData.goods_list;

      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        if (['goods_num', 'goods_num2', 'total_price'].includes(column.key)) {
          let valueProp = prop;
          if (valueProp === 'goods_num2') {
            valueProp = 'goods_num'
          }
          const values = data.map(item => Number(item[valueProp]));
          // if (!values.every(value => isNaN(value))) {
          let unitName = '';
          sums[index] = values.reduce((prev, curr, cIndex) => {
            if (column.key === 'goods_num') {
              unitName = data[cIndex].unit_name;
            }
            else if (column.key === 'goods_num2') {
              const unitNum = data[cIndex].goods_num % data[cIndex].unit_convert2;
              const unitNum2 = Math.floor(data[cIndex].goods_num / data[cIndex].unit_convert2);
              unitName = data[cIndex].unit_name2;
              if (prev && prev.length) {
                return [unitNum + prev[0], unitNum2 + prev[1]]
              }
              return [unitNum, unitNum2]
            }
            // else if (column.key === 'total_price') {
            //   unitName = '元'
            // }

            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (column.key === 'goods_num') {
            sums[index] += unitName;
            this.orderData.total_num = sums[index];
          }
          if (column.key === 'goods_num2' && typeof (sums[index]) === 'object') {
            let goods_num2 = '';
            if (sums[index][1]) {
              goods_num2 = sums[index][1] + data[0].unit_name2
            }
            if (sums[index][0]) {
              goods_num2 = goods_num2 + sums[index][0] + data[0].unit_name
            }
            sums[index] = goods_num2;
          }
          if (column.key === 'total_price') {
            this.orderData.total_price = sums[index];
          }
          // } else {
          //   sums[index] = 'N/A';
          // }
        }
        else {
          sums[index] = '';
        }
      });
      if (prop === 'total_price') {
        this.moneyStr = this.transform(sums[index])
      }
      return sums[index]
    },
    // 处理table 单元格显示；
    handleRowResult(prop, row) {
      if (prop === 'goods_name') {
        return `${row?.full_goods_name ? row?.full_goods_name : row?.goods_name} ${row.goods_sku}`
      }
      if (prop === 'goods_num2') {
        if (row.goods_num && row.unit_name2 && row.unit_convert !== row.unit_convert2 && row.unit_convert2) {
          const unitNum = row.goods_num % row.unit_convert2;
          const unitNum2 = Math.floor(row.goods_num / row.unit_convert2);
          let result = '';
          if (unitNum2) {
            result = `${unitNum2}${row.unit_name2}`
          }
          if (unitNum) {
            result = result + `${unitNum}${row.unit_name}`
          }
          return result
        }
        return `${row.goods_num}${row.unit_name}`
      }
      if (prop === 'unit_convert2') {
        if (row.unit_convert && row.unit_convert2) {
          return `${row.unit_convert} * ${row.unit_convert2} ${row.unit_name}`
        }
        return '';
      }
      return row[prop] || '';
    },
    detail() {
      // bidder.printForm(this.$route.params.objectId).then((res) => {
      //   this.bidder = res.data.detail
      //   this.upperShouldReturnAmount = res.data.upperShouldReturnAmount
      // })
    },
    print() {
      this.$print(this.$refs.printBox)
      // bidder.print(this.$route.params.objectId).then((res) => {
      //   if (res.data.resCode === '0000') {
      //     this.$print(this.$refs.printBox)
      //   } else {
      //     this.$message({
      //       type: 'error',
      //       message: '打印失败，请稍后重试!'
      //     })
      //   }
      // })
    }
  }
}
</script>
<style madia="print">
.print-form {
  background: #eee;
  padding-top: 30px;
}
.print-btn {
  margin-right: 20px;
  float: right;
}
/* 打印区域样式 */
.print-box {
  font-family: "宋体";
  font-size: 3.5mm;
  width: 240mm;
  /* padding: 15mm 15mm 13mm 25mm; */
  /* padding: 10mm 5mm 5mm; */
  padding: 10mm 5mm;
  margin: 0 auto;
  background: #fff;
}
.print-label {
  font-size: 3.5mm;
  text-align: center;
}
.print-space {
  /* display: inline-block; */
}
.print-reason {
  width: 25mm;
}
.print-bank {
  width: 10mm;
}
.print-money {
  width: 12mm;
}
.print-pay {
  width: 5mm;
}
.print-content {
  font-family: "Avenir", sans-serif;
  font-size: 4mm;
  text-align: left;
}
.print-box-title {
  font-size: 7mm;
  letter-spacing: 1.5mm;
  text-align: center;
  /* font-weight: 500; */
  text-decoration: underline;
}
.print-box-company {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 5mm 0 0;
  text-align: left;
  letter-spacing: 0.5mm;
}
.print-box-date {
  /* float: right; */
  display: flex;
  flex-direction: column;
}
.print-box-date .order_no {
  text-decoration: underline;
  text-align: right;
  margin-bottom: 1mm;
}
.print-box-date span {
  display: inline-block;
  width: 15mm;
}
.print-box table {
  width: 100%;
  border: 0.5mm solid black;
  border-collapse: collapse;
}
.print-box table tr {
  height: 6mm;
}
.print-box table td {
  height: 6mm;
  border: 0.3mm solid black;
  padding: 1mm;
}
.print-box .td-label-l {
  width: 38mm;
}
.print-box .td-label-c {
  width: 31mm;
}
.print-box .print-box-foot {
  padding-top: 2mm;
}
.print-box .print-box-foot .foot-label {
  float: left;
  /* width: 25%; */
  width: 33.33%;
  text-align: left;
}

.print-box .td-label-l.moneyStr {
  text-align: left;
  text-indent: 5mm;
}
</style>
